﻿using System;
using System.Collections.Generic;
using CiStatus.CiStatusAddIn.Logic.PluginInterfaces;
using CiStatus.CiStatusAddIn.Logic.Status;
using Sharp2City;

namespace TeamCity
{
    public class TeamCityPoller : ICiPoller
    {
    	private readonly IDictionary<string, ICiPollerParameter> _parameters;
    	private TeamCityClient _teamCityClient;
        private TeamCityBuildConfiguration _buildConfiguration;

    	public TeamCityPoller(IDictionary<string, ICiPollerParameter> parameters)
    	{
    		_parameters = parameters;
    	}

    	public IStatus CurrentStatus()
        {
    	    var lastBuild = _teamCityClient.GetLastBuild(_buildConfiguration);
    	    var lastSuccessfulBuild = _teamCityClient.FindLastSuccessfulBuild(_buildConfiguration);

            var estimatedTime = lastSuccessfulBuild.FinishDate.Subtract(lastSuccessfulBuild.StartDate).TotalSeconds;
            var duration = DateTime.Now.Subtract(lastBuild.StartDate).TotalSeconds;

    	    var details = new StatusDetails()
    	                      {
    	                          Activity = "Success",
    	                          BuildLabel = lastBuild.BuildId.ToString(),
    	                          BuildStatus = "Success",
    	                          BuildTime = DateTime.Now,
    	                          Details = lastBuild.StatusText,
    	                          Message = "M",
    	                          Progress = new Progress(estimatedTime, duration)
            };
            
            if(lastBuild.BuildStatus == BuildStatus.Success)
            {
                return new StatusSuccess(details);
            }
            if (lastBuild.BuildStatus == BuildStatus.Failed)
            {
                return new StatusFailed(details);
            }
            
            return new StatusBuilding(details);
        }

        public void Connect()
        {
            _teamCityClient = new TeamCityClient(_parameters["Server"].Value, _parameters["User"].Value, _parameters["Password"].Value);
            var p = _teamCityClient.FindProject(_parameters["Project"].Value);
            _buildConfiguration = _teamCityClient.FindBuildConfiguration(p, _parameters["SubProject"].Value);
        }

    	public IDictionary<string, ICiPollerParameter> Parameters
    	{
    		get { return _parameters; }
    	}
    }
}
